#include "SocketServer.h"

#include <QDataStream>

#include "com/QueueMananger.h"

SocketServer::SocketServer( QHostAddress host, qint16 port ) :
    QObject( 0 )
{
    this->host = host;
    this->port = port;

    socket = new QUdpSocket( this );
    socket->bind( this->host, this->port, QUdpSocket::ShareAddress );


    connect(socket, SIGNAL( readyRead() ), this, SLOT( readyRead() ) );
    connect(socket, SIGNAL( error( QAbstractSocket::SocketError ) ), this, SLOT( displayError( QAbstractSocket::SocketError ) ) );
}

SocketServer::~SocketServer()
{
    if ( socket )
    {
        delete socket;
    }
}


void SocketServer::readyRead()
{
    if ( !socket->hasPendingDatagrams() )
    {
        return;
    }

    QByteArray buffer( socket->pendingDatagramSize(), 0 );
    socket->readDatagram( buffer.data(), buffer.size() );

    QueueMananger::get()->pushResponse( buffer );
}

void SocketServer::displayError( QAbstractSocket::SocketError socketError )
{
    Q_UNUSED( socketError );
}

